While it is possible to define a struct
with member functions in C++, the general expectation is that struct
s only
aggregate data, while classes are used for fully encapsulated abstractions, containing data and methods. Thus, including a member function in a
struct
is likely to lead to confusion at best and should be avoided.
Noncompliant code example
struct S
{
S(int x, int y) : x(x), y(y) {}
int x;
int y;
public:
int fun(); // Noncompliant
};
Compliant solution
struct S
{
S(int x, int y) : x(x), y(y) {}
int x;
int y;
};
Exceptions
- Constructors are ignored for this rule, because they are the only way that a
struct
designer can enforce that all fields of a
struct
are correctly initialized.
- Overload of the function operator '()'. It is a common practice to use struct as a functor.